<?
header('Content-Type: text/html; charset=UTF-8');
require 'crawl.php';
require 'database.php';
$db = new DB();

$getNow = new DateTime('now');
$today = $getNow->format('Y-m-d');

$cat = isset($_GET['c']) ? strval($_GET['c']) : NULL;
$cat = str_replace(' ', '+', $cat);
$p = isset($_GET['p']) ? strval($_GET['p']) : 0;

if ($p > 10){
	echo 'Done';
	exit();
}

$page = '';
if ($p)
	$page = '/' . $p;

$url = 'http://www.gamepilot.com/games/' . $cat . $page;

//$url = 'http://www.paisdelosjuegos.es/juegos/' . $cat . $page;

$page = crawl($url, $cat);

if ($page == 40) {
	if ($p > 1)
		$page = '&p=' . ($p + 1);
	else
		$page = '&p=2';

//	echo '/_crawl/index.php?c=' . $cat . $page;
	header('Location: /_crawl/index.php?c=' . $cat . $page, true, 301);
	exit();
}
//exit();
function crawl($url, $cat = '') {
	global $db, $today, $p;
	$array = array();

	$html = file_get_html($url);

	if ($html->find('div#games-container-category', 0))
		$string = $html->find('div#games-container-category', 0)->innertext;
	else
		$string = '';

	if (!$string) {
		return false;
		$html->clear();
		unset($html);
	}

	$str = str_get_html($string);

	foreach ($str->find('a') as $element){
		$plaintext = trim($element->title);
		$plaintext = str_replace("'", '', $plaintext);
		$link = trim($element->href);

		$array['name'][] = $plaintext;
		$array['url'][] = $link;
	}

	foreach ($str->find('img') as $element){
		$img = trim($element->src);
		$array['image'][] = $img;
	}

//	echo '<pre>';
// 	print_r($array);
// 	echo '</pre>';
//	exit();

	$total = count($array['url']);

	$num = 0;
	for ($i = 0; $i < $total; $i++) {
		// check url exists
		$Qry = 'SELECT crawl_url
				FROM games
				WHERE crawl_url = "' . $array['url'][$i] . '"';

		if ($db->numRows($Qry) == 0) {
			++$num;

			$name_seo = str_replace(' ', '-', $array['name'][$i]);
			$name_seo = strtolower($name_seo);

			$data = array(
					'name'=>$array['name'][$i],
					'name_seo'=>$name_seo,
					'image'=>$array['image'][$i],
					'tags'=>$cat = str_replace('+', '-', $cat),
					'date'=>$today,
					'crawl_url'=>$array['url'][$i]
			);

// 			echo '<pre>';
// 			print_r($data);
// 			echo '</pre>';

			$newID = $db->insert('games', $data);

			if ($newID) {
				$des = array(
						'id'=>$newID
				);
				$db->insert('games_description', $des);
			}
		}
	}

	echo 'Total games added: ' . $num . ' on page ' . $p;
	return $num;
}